<template>
  <div class="donor-editor" v-reveal="{ delay: 60 }">
    <div class="container">
      <el-page-header @back="goBack" title="返回管理后台">
        <template #content>
          <span class="page-title">捐赠者管理</span>
        </template>
      </el-page-header>
      
      <div class="editor-content" v-reveal="{ delay: 120 }">
        <el-row :gutter="20">
          <el-col :xs="24" :lg="16">
            <el-card v-reveal="{ delay: 160, distance: 12 }">
              <template #header>
                <div class="card-header">
                  <h2>{{ isEditing ? '编辑捐赠者' : '添加捐赠者' }}</h2>
                  <el-button type="primary" @click="saveDonor" :loading="saving">
                    {{ isEditing ? '更新' : '保存' }}
                  </el-button>
                </div>
              </template>
              
              <el-form :model="donorForm" :rules="formRules" ref="formRef" label-width="100px">
                <el-form-item label="捐赠者姓名" prop="name">
                  <el-input v-model="donorForm.name" placeholder="请输入捐赠者姓名" />
                </el-form-item>
                
                <el-form-item label="捐赠金额" prop="amount">
                  <el-input-number
                    v-model="donorForm.amount"
                    :min="1"
                    :precision="2"
                    :step="10"
                    placeholder="请输入捐赠金额"
                    style="width: 100%;"
                  />
                </el-form-item>
                
                <el-form-item label="捐赠日期" prop="date">
                  <el-date-picker
                    v-model="donorForm.date"
                    type="date"
                    placeholder="选择捐赠日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    style="width: 100%;"
                  />
                </el-form-item>
                
                <el-form-item label="捐赠留言">
                  <el-input
                    v-model="donorForm.message"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入捐赠留言（可选）"
                  />
                </el-form-item>
              </el-form>
            </el-card>
          </el-col>
          
          <el-col :xs="24" :lg="8">
            <el-card v-reveal="{ delay: 200, distance: 12 }">
              <template #header>
                <h3>捐赠者列表</h3>
              </template>
              
              <div class="donor-list">
                <div 
                  v-for="(donor, idx) in donorList" 
                  :key="donor.id"
                  class="donor-item"
                  :class="{ active: selectedDonor?.id === donor.id }"
                  @click="selectDonor(donor)"
                  v-reveal="{ delay: 220 + idx * 60, distance: 8 }"
                >
                  <div class="donor-info">
                    <h4>{{ donor.name }}</h4>
                    <p class="amount">¥{{ donor.amount }}</p>
                    <p class="date">{{ donor.date }}</p>
                    <p v-if="donor.message" class="message">{{ donor.message }}</p>
                  </div>
                  <div class="donor-actions">
                    <el-button type="primary" size="small" @click.stop="editDonor(donor)">
                      编辑
                    </el-button>
                    <el-button type="danger" size="small" @click.stop="deleteDonor(donor.id)">
                      删除
                    </el-button>
                  </div>
                </div>
              </div>
              
              <div class="add-new">
                <el-button type="success" @click="addNewDonor" style="width: 100%;">
                  添加新捐赠者
                </el-button>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getDonorData } from '../api/serverApi'

export default {
  name: 'DonorEditor',
  setup() {
    const router = useRouter()
    const formRef = ref()
    const donorList = ref([])
    const selectedDonor = ref(null)
    const isEditing = ref(false)
    const saving = ref(false)
    
    const donorForm = ref({
      id: null,
      name: '',
      amount: 0,
      date: '',
      message: ''
    })
    
    const formRules = {
      name: [
        { required: true, message: '请输入捐赠者姓名', trigger: 'blur' }
      ],
      amount: [
        { required: true, message: '请输入捐赠金额', trigger: 'blur' }
      ],
      date: [
        { required: true, message: '请选择捐赠日期', trigger: 'change' }
      ]
    }
    
    const goBack = () => {
      router.push('/admin')
    }
    
    const loadDonors = () => {
      donorList.value = getDonorData()
    }
    
    const addNewDonor = () => {
      isEditing.value = false
      selectedDonor.value = null
      donorForm.value = {
        id: Date.now(),
        name: '',
        amount: 0,
        date: new Date().toISOString().split('T')[0],
        message: ''
      }
    }
    
    const selectDonor = (donor) => {
      selectedDonor.value = donor
    }
    
    const editDonor = (donor) => {
      isEditing.value = true
      selectedDonor.value = donor
      donorForm.value = { ...donor }
    }
    
    const deleteDonor = async (id) => {
      try {
        await ElMessageBox.confirm('确定要删除这个捐赠者记录吗？', '确认删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        donorList.value = donorList.value.filter(item => item.id !== id)
        if (selectedDonor.value?.id === id) {
          selectedDonor.value = null
          addNewDonor()
        }
        
        localStorage.setItem('donorData', JSON.stringify(donorList.value))
        ElMessage.success('捐赠者记录删除成功')
      } catch (error) {
        // 用户取消删除
      }
    }
    
    const saveDonor = async () => {
      if (!formRef.value) return
      
      try {
        await formRef.value.validate()
        saving.value = true
        
        if (isEditing.value) {
          const index = donorList.value.findIndex(item => item.id === donorForm.value.id)
          if (index !== -1) {
            donorList.value[index] = { ...donorForm.value }
          }
          ElMessage.success('捐赠者信息更新成功')
        } else {
          donorList.value.unshift({ ...donorForm.value })
          ElMessage.success('捐赠者添加成功')
        }
        
        localStorage.setItem('donorData', JSON.stringify(donorList.value))
        addNewDonor()
      } catch (error) {
        console.error('保存失败:', error)
      } finally {
        saving.value = false
      }
    }
    
    onMounted(() => {
      loadDonors()
      addNewDonor()
    })
    
    return {
      formRef,
      donorList,
      selectedDonor,
      isEditing,
      saving,
      donorForm,
      formRules,
      goBack,
      addNewDonor,
      selectDonor,
      editDonor,
      deleteDonor,
      saveDonor
    }
  }
}
</script>

<style scoped>
.donor-editor {
  padding: 20px 0;
}

.page-title {
  font-size: 1.5rem;
  font-weight: bold;
  color: #4CAF50;
}

.editor-content {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  color: #4CAF50;
  margin: 0;
}

.donor-list {
  max-height: 400px;
  overflow-y: auto;
}

.donor-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 8px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: all 0.3s;
}

.donor-item:hover {
  border-color: #4CAF50;
  background: #f9f9f9;
}

.donor-item.active {
  border-color: #4CAF50;
  background: #e8f5e8;
}

.donor-info h4 {
  margin: 0 0 5px 0;
  color: #333;
  font-size: 1rem;
}

.donor-info .amount {
  margin: 0 0 5px 0;
  color: #4CAF50;
  font-weight: bold;
  font-size: 1.1rem;
}

.donor-info .date {
  margin: 0 0 5px 0;
  color: #999;
  font-size: 0.9rem;
}

.donor-info .message {
  margin: 0;
  color: #666;
  font-size: 0.9rem;
  font-style: italic;
}

.donor-actions {
  display: flex;
  gap: 5px;
}

.add-new {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    gap: 15px;
  }
  
  .donor-item {
    flex-direction: column;
    text-align: center;
    gap: 10px;
  }
  
  .donor-actions {
    justify-content: center;
  }
}
</style> 